package com.spzx.product.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.spzx.product.api.domain.Category;
import com.spzx.product.service.CategoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class CategoryExcelDataReadListener extends AnalysisEventListener<Category> {

    private List<Category> categories =new ArrayList<>();
    private int limit = 100;
    @Resource
    CategoryService categoryService;

    public CategoryExcelDataReadListener(CategoryService categoryService){
        this.categoryService = categoryService;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void invoke(Category category, AnalysisContext analysisContext) {
        //检验读取到的数据  是不是已存在  如果id已存在  或者 parent_id下  改名称的分类已存在
       if( categoryService.cateExit(category)){
           //如果读取的数据已存在  则不保存  直接返回
            log.info("数据已存在", JSON.toJSONString(category));
            return;
       }


        categories.add(category);
        //判断是否触发阈值  批量保存
        if (categories.size()>=limit){
            categoryService.saveBatch(categories);
            categories.clear();
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (categories.size()>=0){
            categoryService.saveBatch(categories);
            categories.clear();
        }
    }
}
